package demo1.web.servlet.userBuyapi;

import demo1.dao.Mapper.goodsMapper;
import demo1.dao.Mapper.userBuyMapper;
import demo1.pojo.gouwucar;
import demo1.pojo.userBuy;
import demo1.dao.sql.goodssql;
import demo1.dao.sql.userBuysql;
import demo1.service.userBuyService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/payOrderForm")
public class payOrderForm extends HttpServlet {//支付订单
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        //获取session对象
        HttpSession session = req.getSession();
        Object userObject = session.getAttribute("users");
        userBuy users = (userBuy) userObject;

        try {
            userBuyService pay = new userBuyService();
            int num = pay.checkTime(users.getGouwuid());
            if(num == 1){//时间还没有到
                //检查钱够不够
                int temp = pay.checkMoney(users.getGouwuid(), users.getMoney());
                if(temp == 0){
                    //钱不够
                    resp.sendRedirect("/logindemo2/failPayMoney.jsp");//重定向去充值页面
                }
                else {//钱够了
                    int newmoney = pay.updateMoney(users.getGouwuid(), users.getMoney());//更新钱
                    pay.deleteOrderForm(users.getGouwuid());//删除订单
                    pay.checkGoodsStatue(users.getGouwuid());//检查商品状态，如果是下架就删除商品
                    users.setMoney(newmoney);
                    resp.sendRedirect("paySuccess.jsp");//重定向去支付成功页面
                }
            }
            else if(num == 0){
                //时间到了
                pay.increase(users.getGouwuid());//商品回退到原来的状态
                pay.deleteOrderForm(users.getGouwuid());//取消订单

                resp.sendRedirect("failTimePass.jsp");//重定向去超时页面
            }
            else if(num == -1){
                //没有订单
                resp.sendRedirect("failsearch.jsp");//重定向页面
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
